﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Luka;

/// <summary>
/// 跨域
/// </summary>
[NotScanned]
public static class CorsSetup
{
    /// <summary>
    /// 基本跨域
    /// </summary>
    public static IServiceCollection AddCors(this IServiceCollection services)
    {
        var setting = InternalApp.GetSection<CorsOptions>("Cors");
        if (setting != null)
        {
            services.AddCors(cor =>
            {
                cor.AddPolicy(setting?.PolicyName ?? $"{InternalApp.ProgramName}_Policy_Cors", policy =>
                {
                    policy.SetIsOriginAllowed(_ => true)
                        .SetIsOriginAllowedToAllowWildcardSubdomains();
                    //如果没有配置请求域名，则允许所有
                    if (setting?.WithOrigins != null && setting.WithOrigins.Length > 0)
                    {
                        policy.WithOrigins(setting.WithOrigins);
                    }
                    else
                    {
                        policy.AllowAnyOrigin();
                    }
                    //如果没有设置请求头部，则允许所有头部
                    if (setting?.WithHeaders != null && setting.WithHeaders.Length > 0)
                    {
                        policy.WithHeaders(setting.WithHeaders);
                    }
                    else
                    {
                        policy.AllowAnyHeader();
                    }
                    //如果没有配置响应方法，则允许所有方法
                    if (setting?.WithMethods != null && setting.WithMethods.Length > 0)
                    {
                        policy.WithMethods(setting.WithMethods);
                    }
                    else
                    {
                        policy.AllowAnyMethod();
                    }
                });
            });
        }
        else
        {
            services.AddCors(cor =>
            {
                cor.AddPolicy($"{InternalApp.ProgramName}_Policy_Cors", policy =>
                {
                    policy.SetIsOriginAllowed(_ => true)
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });
        }
        return services;
    }

    /// <summary>
    /// 使用跨域
    /// </summary>
    public static IApplicationBuilder UseCorsAccessor(this IApplicationBuilder app)
    {
        var policyName = InternalApp.GetSection("Cors:PolicyName");
        if (!string.IsNullOrEmpty(policyName))
        {
            app.UseCors(policyName);
        }
        else
        {
            app.UseCors($"{InternalApp.ProgramName}_Policy_Cors");
        }
        return app;
    }
}